package com.cocos.game;

import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MyUtils {
    //=============sysinfo相关===============
    public static JSONObject getSystemInfo(Context context) {
        JSONObject result = new JSONObject();
        try {
            try {
                // CPU信息
                result.put("cpuInfo", getCpuInfo());
            } catch (Exception e) {
            }
            try {
                // GPU信息
                JSONObject gpuJson = new JSONObject();
//            String renderer = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
//                    .getDeviceConfigurationInfo().getGlEsVersion();
                gpuJson.put("renderer", "ARM");
                gpuJson.put("vender", getGpuVendor(context));
                result.put("gpuInfo", gpuJson.toString());
            } catch (Exception e) {
            }
            try {
                // RAM信息
                JSONObject ramInfo = new JSONObject();
                ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
                ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                activityManager.getMemoryInfo(memoryInfo);
                ramInfo.put("total", bytesToGB(memoryInfo.totalMem));
                ramInfo.put("occupied", bytesToGB(memoryInfo.totalMem - memoryInfo.availMem));
                result.put("ramInfo", ramInfo);
            } catch (Exception e) {
            }
            try {
                // ROM信息
                JSONObject romInfo = new JSONObject();
                StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
                long totalBytes = statFs.getTotalBytes();
                long availableBytes = statFs.getAvailableBytes();
                romInfo.put("total", bytesToGB(totalBytes));
                romInfo.put("occupied", bytesToGB(totalBytes - availableBytes));
                result.put("romInfo", romInfo);
            } catch (Exception e) {
            }
            try {
                // 系统信息
                result.put("systemInfo", "Android" + Build.VERSION.RELEASE);
            } catch (Exception e) {
            }
            try {
                // 网络信息
                result.put("network", getNetworkType(context));
            } catch (Exception e) {
            }
            try {
                result.put("model", Build.BRAND + Build.MODEL);
                result.put("systemVersion", Build.VERSION.RELEASE);
                result.put("apiLevel", Build.VERSION.SDK_INT);
            } catch (Exception e) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String getCpuInfo() {
        String cpu = Build.HARDWARE;
        if (TextUtils.isEmpty(cpu)) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader("/proc/cpuinfo"));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.contains("Hardware")) {
                        cpu = line.split(":")[1].trim();
                        break;
                    }
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return cpu;
    }

    private static String getGpuVendor(Context ctx) {
        String vendor = "unknown";
        try {
            PackageManager pm = ctx.getPackageManager();
            FeatureInfo[] features = pm.getSystemAvailableFeatures();
            for (FeatureInfo feature : features) {
                if (feature.name != null && feature.name.contains("opengles")) {
                    vendor = feature.name;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vendor;
    }

    private static double bytesToGB(long bytes) {
        return Math.round((bytes / (1024.0 * 1024.0 * 1024.0)) * 100.0) / 100.0;
    }

    private static String getNetworkType(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return "WiFi";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                switch (networkInfo.getSubtype()) {
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        return "4G";
                    case TelephonyManager.NETWORK_TYPE_NR:
                        return "5G";
                    default:
                        return "3G";
                }
            }
        }
        return "unknown";
    }
    //==================end==================
    public static boolean saveImageToGallery(Context context, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            Log.e("SaveImage", "File does not exist: " + filePath);
            return false;
        }

        ContentValues values = new ContentValues();
        ContentResolver resolver = context.getContentResolver();

        // 设置媒体类型
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());

        // 设置目标目录为 Pictures
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

        Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        if (uri == null) {
            Log.e("SaveImage", "Failed to insert MediaStore.");
            return false;
        }

        try (OutputStream os = resolver.openOutputStream(uri);
             InputStream is = new FileInputStream(file)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            Log.d("SaveImage", "Save image success");
            return true;

        } catch (Exception e) {
            Log.e("SaveImage", "Save image failed: " + e.getMessage());
            try {
                resolver.delete(uri, null, null);
            } catch (Exception ignored) {}
            return false;
        }
    }
}
